package com.evan.uyclub.Other;

import static android.content.Context.CLIPBOARD_SERVICE;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.PictureDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.View;

import androidx.appcompat.app.AlertDialog;

import com.downloader.Error;
import com.downloader.OnDownloadListener;
import com.downloader.PRDownloader;
import com.evan.uyclub.R;
import com.github.ybq.android.spinkit.SpinKitView;
import com.github.ybq.android.spinkit.sprite.Sprite;
import com.github.ybq.android.spinkit.style.Wave;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.sdsmdg.tastytoast.TastyToast;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ProgressBar;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.tapadoo.alerter.Alerter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Utlis {

    /**
     * 图片缩放比例
     */
    private static final float BITMAP_SCALE = 0.4f;
    /**
     * 最大模糊度(在0.0到25.0之间)
     */
    private static final float BLUR_RADIUS = 25f;
    public static AlertDialog loadDialog;

    //引用函数，需要在context上面引入
    //比如utlis.Json;
    public static void Json(Context context, String data) {

    }

    public static void Puss(Context context) {
        TastyToast.makeText(context, "欢迎你哦！", TastyToast.LENGTH_SHORT, TastyToast.SUCCESS);
    }

    /**
     * 保存文件到公共目录
     *
     * @param context  上下文
     * @param fileName 文件名
     * @param bitmap   文件
     * @return 路径，为空时表示保存失败
     */
    public static String fileSaveToPublic(Context context, String fileName, Bitmap bitmap) {
        String path = null;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            //Android 10以下版本
            FileOutputStream fos = null;
            try {
                //设置路径 Pictures/
                // File folder = new File("/UyCode/下载的壁纸/");
                File folder = Environment.getExternalStoragePublicDirectory("/UyCode/下载的壁纸/");
                //判断目录是否存在
                //目录不存在时自动创建
                if (folder.exists() || folder.mkdir()) {
                    File file = new File(folder, fileName);
                    fos = new FileOutputStream(file);
                    //写入文件
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    path = file.getAbsolutePath();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            //Android 10及以上版本
            //设置路径 Pictures/
            String folder = Environment.DIRECTORY_PICTURES;
            //设置保存参数到ContentValues中
            ContentValues values = new ContentValues();
            //设置图片名称
            values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
            //设置图片格式
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
            //设置图片路径
            values.put(MediaStore.Images.Media.RELATIVE_PATH, folder);
            //执行insert操作，向系统文件夹中添加文件
            //EXTERNAL_CONTENT_URI代表外部存储器，该值不变
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            OutputStream os = null;
            try {
                if (uri != null) {
                    //若生成了uri，则表示该文件添加成功
                    //使用流将内容写入该uri中即可
                    os = context.getContentResolver().openOutputStream(uri);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                    os.flush();
                    path = uri.getPath();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return path;
    }

    /**
     * 质量压缩方法
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    /**
     * 模糊图片的具体方法
     *
     * @param context 上下文对象
     * @param image   需要模糊的图片
     * @return 模糊处理后的图片
     */
    public static Bitmap blur(Context context, Bitmap image) {
        // 计算图片缩小后的长宽
        int width = Math.round(image.getWidth() * BITMAP_SCALE);
        int height = Math.round(image.getHeight() * BITMAP_SCALE);

        // 将缩小后的图片做为预渲染的图片。
        Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
        // 创建一张渲染后的输出图片。
        Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);

        // 创建RenderScript内核对象
        RenderScript rs = RenderScript.create(context);
        // 创建一个模糊效果的RenderScript的工具对象
        ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));

        // 由于RenderScript并没有使用VM来分配内存,所以需要使用Allocation类来创建和分配内存空间。
        // 创建Allocation对象的时候其实内存是空的,需要使用copyTo()将数据填充进去。
        Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
        Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);

        // 设置渲染的模糊程度, 25f是最大模糊度
        blurScript.setRadius(BLUR_RADIUS);
        // 设置blurScript对象的输入内存
        blurScript.setInput(tmpIn);
        // 将输出数据保存到输出内存中
        blurScript.forEach(tmpOut);

        // 将数据填充到Allocation中
        tmpOut.copyTo(outputBitmap);

        return outputBitmap;
    }

    //二维码生成
    public static Bitmap qrcode(String content) {
        int width = 350;
        int height = 350;
        //HashMap设置二维码参数
        Map map = new HashMap();
        //   设置容错率 L>M>Q>H  等级越高扫描时间越长,准确率越高
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        //设置字符集
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //设置外边距
        map.put(EncodeHintType.MARGIN, 1);
        //利用编码器，生成二维码
        BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
        Bitmap bitmap = null;
        try {
            bitmap = barcodeEncoder.encodeBitmap(content, BarcodeFormat.QR_CODE, width, height, map);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    //判断vpn
    public static boolean isVPNConnected(Context context) {
        List<String> networkList = new ArrayList<>();
        try {
            for (java.net.NetworkInterface networkInterface : java.util.Collections.list(java.net.NetworkInterface.getNetworkInterfaces())) {
                if (networkInterface.isUp()) {
                    networkList.add(networkInterface.getName());
                }
            }
        } catch (Exception ex) {
        }
        return networkList.contains("tun0") || networkList.contains("ppp0");
    }

    //加载弹窗
    //调用弹出   Utlis.LoadingDialog(this);
    public static void LoadingDialog(Context context) {
        try {
            ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
        }
        loadDialog = new MaterialAlertDialogBuilder(context)
                .create();
        final View contentView = View.inflate(context, R.layout.loading, null);
        SpinKitView spinKitView = contentView.findViewById(R.id.spinkv);
        Sprite spinks = new Wave();
        spinKitView.setIndeterminateDrawable(spinks);
        loadDialog.setView(contentView);
        loadDialog.show();
        loadDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
        WindowManager.LayoutParams layoutParams = loadDialog.getWindow().getAttributes();
        layoutParams.width = context.getResources().getDisplayMetrics().widthPixels / 5 * 4;
        layoutParams.height = context.getResources().getDisplayMetrics().widthPixels / 5 * 4;
        loadDialog.getWindow().setAttributes(layoutParams);
    }

    //保存图片
    public static String SaveImage(Context context, Bitmap bitmap, String path, String name) {
        if (bitmap == null) {
            return null;
        }
        @SuppressLint("SimpleDateFormat") final String time = new SimpleDateFormat("HH-mm-ss").format(new Date());
        if (!FileUtil.isExistFile(FileUtil.getExternalStorageDir().concat(path))) {
            FileUtil.makeDir(FileUtil.getExternalStorageDir().concat(path));
        }
        File appDir = new File(FileUtil.getExternalStorageDir().concat(path));
        File file = new File(appDir, name);
        java.io.FileOutputStream fos = null;
        try {
            fos = new java.io.FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (java.io.IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static Bitmap pictureDrawable2Bitmap(PictureDrawable pictureDrawable) {
        //图片背景的画笔
        Paint paint = new Paint();
        paint.setColor(Color.TRANSPARENT);
        //创建bitmap对象
        Bitmap bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(), pictureDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawRect(0, 0, bitmap.getWidth() + 50, bitmap.getHeight() + 50, paint);
        pictureDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        pictureDrawable.draw(canvas);
        return bitmap;
    }


    //dp转px
    public static int dp2px(Context context, float dpValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());
    }

    //下载文件
    public static void Download(Context context, String title, String content, String url, String path, String name) {
        final AlertDialog mDialog = new MaterialAlertDialogBuilder(context)
                .create();
        View contentView = View.inflate(context, R.layout.dialog_download, null);
        mDialog.setTitle(title);
        mDialog.setMessage(content);
        mDialog.setView(contentView);
        mDialog.show();
        final MaterialButton button1 = contentView.findViewById(R.id.button1);
        final MaterialButton button2 = contentView.findViewById(R.id.button2);
        final ProgressBar progressBar = contentView.findViewById(R.id.jdt);
        final TextInputEditText textInputEditText = contentView.findViewById(R.id.textInputEditText);
        final TextInputLayout textInputLayout = contentView.findViewById(R.id.textInputLayout);
        textInputEditText.setText(name);
        textInputEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                textInputLayout.setErrorEnabled(false);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        button1.setText(R.string.取消);
        button1.setBackgroundColor(context.getResources().getColor(R.color.itemBackColor));
        button2.setText(R.string.保存);
        button2.setBackgroundColor(context.getResources().getColor(R.color.zts));
        button1.setOnClickListener(v11 -> {
            mDialog.dismiss();
        });
        button2.setOnClickListener(v11 -> {
            if (TextUtils.isEmpty(textInputEditText.getText())) {
                textInputLayout.setError(context.getString(R.string.请输入文件名称));
                textInputLayout.setErrorEnabled(true);
            } else {
                button2.setText(R.string.请稍等);
                progressBar.setVisibility(View.VISIBLE);
                if (!FileUtil.isExistFile(FileUtil.getExternalStorageDir().concat(path))) {
                    FileUtil.makeDir(FileUtil.getExternalStorageDir().concat(path));
                }
                int downloadIdOne = PRDownloader.download(url, FileUtil.getExternalStorageDir().concat(path), String.valueOf(textInputEditText.getText()))
                        .build()
                        .setOnStartOrResumeListener(() -> {
                        })
                        .setOnPauseListener(() -> {
                        })
                        .setOnCancelListener(() -> {
                        })
                        .setOnProgressListener(progress -> {
                            long progressPercent = progress.currentBytes * 100 / progress.totalBytes;
                            button2.setText(R.string.下载中); // + progressPercent + "％");
                            progressBar.setIndeterminate(false);
                            progressBar.setProgress((int) progressPercent);
                        })
                        .start(new OnDownloadListener() {
                            @Override
                            public void onDownloadComplete() {
                                progressBar.setVisibility(View.GONE);
                                mDialog.dismiss();
                                android.media.MediaScannerConnection.scanFile((Activity) context, new String[]{FileUtil.getExternalStorageDir().concat(path) + textInputEditText.getText()}, null, new android.media.MediaScannerConnection.OnScanCompletedListener() {
                                    public void onScanCompleted(String str, Uri uri) {
                                        Intent intent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
                                        intent.setData(uri);
                                        ((Activity) context).sendBroadcast(intent);
                                        Alerter.create((Activity) context)
                                                .setTitle(R.string.保存成功)
                                                .setText(context.getString(R.string.已保存到) + path + textInputEditText.getText())
                                                .setBackgroundColorInt(context.getResources().getColor(R.color.success))
                                                .show();
                                    }
                                });
                            }

                            @Override
                            public void onError(Error error) {
                            }

                        });
            }
        });
        WindowManager.LayoutParams layoutParams = mDialog.getWindow().getAttributes();
        layoutParams.width = context.getResources().getDisplayMetrics().widthPixels / 10 * 9;
        mDialog.getWindow().setAttributes(layoutParams);
    }

    //截取字符串
    public static String JieQu(Context context, String str1, String str2, String str3) {
        if (!str1.contains(str2) || !str1.contains(str3)) {
            return "";
        }
        String substring = str1.substring(str1.indexOf(str2) + str2.length());
        return substring.substring(0, substring.indexOf(str3));
    }

    //复制弹窗
    public static void CopyDialog(Context context, String little, String content) {
        final AlertDialog mDialog = new MaterialAlertDialogBuilder(context)
                .setPositiveButton(R.string.复制, null)
                .setNegativeButton(R.string.取消, null)
                .create();
        mDialog.setTitle(little);
        mDialog.setMessage(content);
        mDialog.setOnShowListener(dialog -> {
            Button positiveButton = mDialog.getButton(AlertDialog.BUTTON_POSITIVE);
            Button negativeButton = mDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
            positiveButton.setOnClickListener(v -> {
                mDialog.dismiss();
                ((ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE)).setPrimaryClip(ClipData.newPlainText("clipboard", content));
                Alerter.create((Activity) context)
                        .setTitle(R.string.复制成功)
                        .setText(R.string.已成功将内容复制到剪切板)
                        .setBackgroundColorInt(context.getResources().getColor(R.color.success))
                        .show();
            });
            negativeButton.setOnClickListener(v -> mDialog.dismiss());
        });
        mDialog.show();
        WindowManager.LayoutParams layoutParams = mDialog.getWindow().getAttributes();
        layoutParams.width = context.getResources().getDisplayMetrics().widthPixels / 10 * 9;
        mDialog.getWindow().setAttributes(layoutParams);
    }

}
